<template>
  <div class="app-container">
    <div>
      <el-button @click="showUpload" type="success">上传文件</el-button>
      <el-button @click="showNewDir" type="primary">新建目录</el-button>
    </div>
    <div>
      <div style="margin-bottom: 10px;margin-top: 10px;font-size: 24px;">
        <i class="el-icon-back" @click="popDir()" v-if="this.stack.data.length > 1" style="color: #36a3f7"></i>
        <template v-for="(path,index) in stack.data">
          <span :key="index"
                style="color: #36a3f7" @click="anyDir(path,index)" v-if="index!==stack.data.length-1">{{ path.name }}/</span>
          <span :key="index" style="color:#97a8be;" v-if="index===stack.data.length-1">{{ path.name }} /</span>
        </template>

      </div>
<!--      文件列表-->
      <el-table :data="table.data" border v-loading="table.loading">
        <el-table-column label="文件名称" prop="name">
          <template slot-scope="scope">
            <div v-if="scope.row.type===dirType">
              <span @click="pushDir(scope.row)" style="color: #36a3f7">{{scope.row.name}}</span>
            </div>
            <div v-else>
              <span>{{scope.row.name}}</span>
            </div>
          </template>
        </el-table-column>
<!--        <el-table-column label="文件类型" prop="typeText"></el-table-column>-->
        <el-table-column label="添加时间" prop="createdAt" width="200"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="danger" size="medium" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="primary" size="medium" @click="showRename(scope.row)" v-if="scope.row.type===dirType">编辑</el-button>
<!--            <el-button type="success" size="medium" @click="handleDownLoad(scope.row)">下载</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
<!--    新建目录-->
    <el-dialog :visible.sync="createDir.visible" :title="createDir.title" @close="handleCloseDir">
      <el-form>
        <el-form-item label="目录名称">
          <el-input v-model="dirForm.name"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="file">
          <el-upload :action="uploadDialog.action"
                     :headers="uploadDialog.headers"
                     :data = "uploadDialog.iconData"
                     :file-list="uploadDialog.iconList"
                     :limit="1" list-type="picture-card" :on-preview="handleImagePreview" :before-upload="beforeIconUpload" :on-remove="handleIconImageRemove('iconUrl')" :on-success="handleIconUploadSuccess('iconUrl')">
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCreateDir" v-if="createDir.type==='create'">保存</el-button>
          <el-button type="primary" @click="handleRename" v-if="createDir.type==='update'">保存</el-button>
        </el-form-item>
      </el-form>
      <div>
        <h2>说明</h2>
        <div>
          <div>1. 请输入正常的目录名称</div>
          <div>2. 上传新图标之前，请先删除旧图标</div>
        </div>
      </div>
    </el-dialog>
<!--    上传文件-->
    <el-dialog :visible.sync="uploadDialog.visible" :title="uploadDialog.title" @close="handleCloseFile">
      <el-form>
        <el-form-item label="文件" prop="file">
          <el-upload drag :action="uploadDialog.action"
                     :headers="uploadDialog.headers"
                     :data = "uploadDialog.fileData"
                     :file-list="uploadDialog.fileList"
                     :before-upload="beforeUpload"
                     :limit="1"  :on-preview="handleImagePreview" :on-remove="handleImageRemove('url')" :on-success="handleUploadSuccess('url')">
            <i class="el-icon-upload"></i>
          </el-upload>
          <div style="color: red">{{ uploadDialog.errMessage }}</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCreateFile">保存</el-button>
        </el-form-item>
      </el-form>
      <div>
        <h2>说明</h2>
        <div>1. 同一目录文件名不可重复，重复上传会覆盖旧的</div>
        <div>2. 请使用正确的扩展名，防止客户端无法查看</div>
        <div>3. 支持pdf,word,excel,ppt</div>
        <div>4. 上传新文件之前，请先删除旧文件</div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { createFile, deleteFile, getFileList, updateFileName } from '../../api/file'

  const dirType = 99
  const initDirForm = () => {
    return {
      pid: 0,
      name: '',
      url: '',
      iconUrl: '',
      type: dirType
    }
  }
  const initUploadForm = () => {
    return {
      pid: 0,
      type: 0,
      pathIds: '',
      url: '',
      iconUrl: '',
      name: ''
    }
  }
  export default {
    data() {
      return {
        table: {
          data: [],
          loading: false
        },
        dirType: dirType,
        stack: (() => {
          return {
            data: [
              {
                name: '',
                id: 0
              }
            ],
            bottom:{
              id: 0,
              name: ''
            },
            top: {
              id: 0,
              name: ''
            }
          }
        })(),
        path: '',
        currentRow: {},
        parentRow: {},
        createDir: {
          visible: false,
          title: '新建目录',
          id: 0,
          type: 'create'
        },
        dirForm: initDirForm(),
        uploadDialog: {
          visible: false,
          title: '上传文件',
          errMessage: '',
          fileData: {
            type: 1,
            p: 'files'
          },
          iconData: {
            type: 2,
            p: 'icons'
          },
          fileList: [],
          iconList: [],
          headers: {},
          action: '/files/upload'
        },
        uploadForm: initUploadForm()
      }
    },
    computed: {
      paths() {
        return this.path.split('/')
      }
    },
    mounted() {
      this.getFileList({
        pid: 0
      })
    },
    methods: {
      handleRename() {
        updateFileName({
          name: this.dirForm.name,
          iconUrl: this.dirForm.iconUrl
        }, this.createDir.id).then(() => {
          this.$message.success('操作成功')
          this.createDir = initDirForm()
          this.getList()
        })
      },
      showRename(row) {
        this.dirForm.name = row.name
        this.dirForm.iconUrl = row.iconUrl
        this.createDir.title = '更新目录'
        this.createDir.id = row.id
        this.createDir.type = 'update'
        this.createDir.visible = true
        if (row.iconUrl.length > 0) {
          this.uploadDialog.iconList.push({
            url: row.iconUrl,
            id: row.iconUrl
          })
        }
      },
      handleCloseDir() {
        this.dirForm = initDirForm()
        this.uploadDialog.iconList = []
      },
      handleCloseFile() {
        this.uploadForm = initUploadForm()
        this.uploadDialog.fileList = []
      },
      handleCreateFile() {
        if (this.uploadDialog.fileList.length === 0) {
          this.uploadDialog.errMessage = '请先上传文件'
          return
        }
        this.uploadForm.pid = this.stack.top.id
        createFile(this.uploadForm).then(() => {
          this.uploadDialog.errMessage = ''
          this.$message.success('操作成功')
          this.createDir.visible = false
          this.uploadForm = initUploadForm()
          this.getList()
          this.uploadDialog.visible = false
          this.uploadDialog.fileList = []
        })
      },
      popDir() {
        this.stack.data.pop()
        this.stack.top = this.stack.data[this.stack.data.length-1]
        this.table.loading = true
        this.getFileList({
          pid: this.stack.top.id
        }).then(res => {
          this.table.data = res.data
        }).finally(() => {
          this.table.loading = false
        })
      },
      anyDir(row, index) {
        this.stack.data = this.stack.data.splice(0, index + 1)
        this.stack.top = row
        this.table.loading = true
        this.getFileList({
          pid: row.id
        }).then(res => {
          this.table.data = res.data
        }).finally(() => {
          this.table.loading = false
        })
      },
      handleCreateDir() {
        this.dirForm.pid = this.stack.top.id
        this.dirForm.type = this.dirType
        createFile(this.dirForm).then(() => {
          this.$message.success('操作成功')
          this.dirForm = initDirForm()
          this.createDir.visible = false
          this.uploadDialog.iconList = []
          this.table.loading = true
          this.getFileList({
            pid: this.stack.top.id
          }).then(res => {
            this.table.data = res.data
          }).finally(() => {
            this.table.loading = false
          })
        })
      },
      handleDownLoad(row) {
        const aTag = document.createElement('a')
        aTag.download = 'test.png'
        aTag.href = 'https://static.oss.sx985.com/files/2020/04/16/03a7c7f424f2ed900ca0079df5326666.png'
        // aTag.addEventListener('click', () => {})
        console.log(aTag)
        aTag.click()
      },
      handleDelete(row) {
        this.$confirm('您正在进行删除操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteFile(row.id).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handleImagePreview(file) {
        this.imageDialog.url = file.url
        this.imageDialog.visible = true
      },
      handleUploadSuccess(name) {
        return (response, file, fileList) => {
          if (response.code > 0) {
            this.$message.error(response.message)
          } else {
            this.uploadForm[name] = response.data.path
            this.uploadForm['name'] = response.data.name
            this.uploadForm['type'] = response.data.type
          }
          console.log(response, file, fileList)
        }
      },
      beforeUpload() {
        if (this.uploadDialog.fileList.length > 0) {
          this.uploadDialog.errMessage = '请先保存或删除上传列表中的文件'
          return false
        }
      },
      beforeIconUpload() {
        if (this.uploadDialog.iconList.length > 0) {
          this.uploadDialog.errMessage = '请先保存或删除上传列表中的文件'
          this.$message.error('请先保存或删除上传列表中的文件')
          return false
        }
      },
      handleImageRemove(name) {
        return (file, fileList) => {
          this.uploadForm[name] = ''
          this.uploadDialog.errMessage = ''
        }
      },
      handleIconUploadSuccess(name) {
        return (response, file, fileList) => {
          if (response.code > 0) {
            this.$message.error(response.message)
          } else {
            this.dirForm[name] = response.data.path
            // this.dirForm['name'] = response.data.name
          }
          console.log(response, file, fileList)
        }
      },
      handleIconImageRemove(name) {
        return (file, fileList) => {
          this.uploadDialog.iconList = []
          this.dirForm[name] = ''
        }
      },
      getList() {
        this.table.loading = true
        this.getFileList({
          pid: this.stack.top.id
        }).then(res => {
          this.table.data = res.data
        }).finally(() => {
          this.table.loading = false
        })
      },
      getFileList(params) {
        return getFileList(params).then(res => {
          this.table.data = res.data
          return res
        })
      },
      pushDir(row) {
        this.stack.top = row
        this.stack.data.push(row)
        this.getList()
      },
      showUpload() {
        this.uploadDialog.visible = true
      },
      showNewDir() {
        this.createDir.title = '新建目录'
        this.createDir.visible = true
      }
    }
  }
</script>
